/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.example.a12502.aihome.home;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author asus
 */
public class Mysql {

    private static Connection conn;
    private static ResultSet rs = null;

    public Mysql() {
        try {
            Class.forName("com.mysql.jdbc.Driver"); //加载数据库连接驱动
            String user = "root";
            String psw = "123456";  //XXX为自己的数据库的密码
            String url = "jdbc:mysql://120.79.205.71:3306/flu?useUnicode=true&characterEncoding=UTF-8";                   //ZZZ为连接的名字
            this.conn = DriverManager.getConnection(url, user, psw);  //获取连接
            System.out.println("连接");
        } catch (Exception e) {
            System.out.println("连接数据库失败");
            e.printStackTrace();
        }
    }

    public Map<String, Object> query() throws SQLException {

        Map<String, Object> temp = new HashMap<String, Object>();
        String sqlInset = "SELECT Max(time) time,any_value(state) state from test";
        try {
            PreparedStatement stmt = this.conn.prepareStatement(sqlInset);   //会抛出异常
            rs = stmt.executeQuery();
            while (rs.next()) {
                temp.put("state", rs.getString("state"));
                temp.put("time", rs.getString("time"));

            }

        } catch (SQLException ex) {
            Logger.getLogger(Mysql.class.getName()).log(Level.SEVERE, null, ex);
        }
        return temp;
    }

    public void close() throws SQLException {
        this.conn.close();
    }
}
